// components/progress-bar/progress-bar.js
let movableAreaWidth = 0
let movableViewWidth = 0
const backgroundAudioManager = wx.getBackgroundAudioManager()
let currentSec = -1 //当前的秒数
let duration = 0 // 当前歌曲的总时长，以秒为单位
let isMoving = false //表示当前是否在进行拖拽
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    showTime: {
      currentTime: '00:00',
      totalTime: '00:00',
    },
    movableDis: 0,
    progress: 0, //当前进度条移动距离
  },
  // 生命周期函数
  lifetimes: {
    ready() {
      this._getMovableDis()
      this._bindBGMevent()
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onChange(event){
      //  touch 是拖动的时候
      if (event.detail.source == 'touch') {
        this.data.progress = event.detail.x / (movableAreaWidth - movableViewWidth) * 100
        this.data.movableDis = event.detail.x
        isMoving = true
      }
    },
    onTouchEnd(){

      // 设置播放时间
      const currentTimeFmt = this._dateFormat(Math.floor(backgroundAudioManager.currentTime))
      this.setData({
        progress: this.data.progress, //移动距离
        movableDis: this.data.movableDis, //
        ['showTime.currentTime']: currentTimeFmt.min + ':' + currentTimeFmt.sec
        // 已经播放时长
      })
      backgroundAudioManager.seek(duration * this.data.progress / 100)
      isMoving = false


    },
    _getMovableDis() {
      const query = this.createSelectorQuery()
      query.select('.movable-area').boundingClientRect()
      query.select('.movable-view').boundingClientRect()
      query.exec((rect) => {
        movableAreaWidth = rect[0].width
        movableViewWidth = rect[1].width
        
      })
    },
    _bindBGMevent() {
      backgroundAudioManager.onPlay(() => {
          // 播放开始的时候
          
          isMoving = false
        }),
        backgroundAudioManager.onStop(() => {
          // 播放停止的时候
          
        }),
        backgroundAudioManager.onPause(() => {
          // 播放暂停的时候
          
        }),
        backgroundAudioManager.onWaiting(() => {
          // 当前音频正在加载中
          
        }),
        backgroundAudioManager.onCanplay(() => {
          // 当前音频处于可以播放的时候
          
          
          if (typeof backgroundAudioManager.duration != 'undefined') {
            this._setTime()
          } else {
            setTimeout(() => {
              this._setTime()
            }, 1000)
          }
        }),
        backgroundAudioManager.onTimeUpdate(() => {
          // 监听音乐播放进度（只有小程序在前台的时候才生效）
          // 
          if(!isMoving){
            const currentTime = backgroundAudioManager.currentTime
            const duration = backgroundAudioManager.duration
            const sec = currentTime.toString().split('.')[0]
            if( sec != currentSec){
               const currentTimeFmt = this._dateFormat(currentTime)
              this.setData({
                movableDis :  (movableAreaWidth - movableViewWidth) * currentTime / duration,
                progress: currentTime / duration * 100,
                ['showTime.currentTime'] : `${currentTimeFmt.min}:${currentTimeFmt.sec}`
              });
              currentSec = sec
            }
          }
      
      
        }),
        backgroundAudioManager.onEnded(() => {
          // 监听音乐播放完成之后
          
          this.triggerEvent('misucEnd')
        }),
        backgroundAudioManager.onError((res) => {
          // 监听音乐播放出现问题的时候
          
          
          wx.showToast({
            title: '错误' + res.errCode
          })
        })
    },
    _setTime() {
      duration = backgroundAudioManager.duration
      
      const dataFromat = this._dateFormat(duration)
      
      this.setData({
        ['showTime.totalTime']:`${dataFromat.min}:${dataFromat.sec}`
      })

    },
    // 格式化时间
    _dateFormat(sec){
      let min = Math.floor(sec / 60)
      sec = Math.floor(sec % 60)
      return {
        min:this._parse0(min),
        sec:this._parse0(sec)
      }
    },
    _parse0(sec){
      // 补零
      return sec < 10 ? '0' + sec : sec
    }
  }
})